package vip.zhenzicheng.test.juc.atomic;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 配合 CountDownLatch 实现更优雅的计算等待
 *
 * @author zhenzicheng
 * @date 2022-09-06 20:59
 */
public class AtomicIntegerCase {

  private static final int SIZE = 50;

  public static void main(String[] args) throws InterruptedException {
    MyNumber myNumber = new MyNumber();
    CountDownLatch countDownLatch = new CountDownLatch(SIZE);

    for (int i = 0; i < SIZE; i++) {
      new Thread(() -> {
        try {
          for (int j = 0; j < 1000; j++) {
            myNumber.addPlusPlus();
          }
        } finally {
          countDownLatch.countDown();
        }
      }, String.valueOf(i)).start();
    }

    // 暂停为了等待上面计算结束，否则永远小于结果值
    // try {
    //   TimeUnit.SECONDS.sleep(1);
    // } catch (InterruptedException e) {
    //   e.printStackTrace();
    // }
    countDownLatch.await();
    System.out.println(Thread.currentThread().getName() + "\tresult: " + myNumber.atomicInteger.get());
  }
}

class MyNumber {

  AtomicInteger atomicInteger = new AtomicInteger();

  public void addPlusPlus() {
    atomicInteger.getAndIncrement();
  }
}

